package com.cdn.log.aspect;

import com.cdn.log.consts.CLogConst;
import com.cdn.log.mq.Message;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

import java.lang.reflect.Field;

/**
 * @author 蔡定努
 * 2024/06/01 23:21
 */
@ConditionalOnClass(RabbitTemplate.class)
@Aspect
public class RabbitmqAspect {

    @Around("@annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)")
    public Object beforeRabbitListener(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                if (arg instanceof Message) {
                    Message<?> message = (Message<?>) arg;
                    Class<? extends Message> aClass = message.getClass();
                    Field field = aClass.getDeclaredField(CLogConst.TRACE_ID);
                    field.setAccessible(true);
                    Object fieldValue = field.get(message);
                    if (fieldValue == null) {
                        fieldValue = "";
                    }
                    MDC.put(CLogConst.TRACE_ID, fieldValue + "");
                }
            }
        } catch (Exception ignored) {

        }
        Object proceed = joinPoint.proceed();
        MDC.clear();
        return proceed;
    }

}
